package com.dunqi.gpm.cangxi.home.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.common.base.ComObserver;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;
import com.dunqi.gpm.cangxi.develop.widget.DrawLeftRadioButton;
import com.dunqi.gpm.cangxi.develop.widget.ThreeInOne;
import com.dunqi.gpm.cangxi.home.adapter.ViewPagerFragmentAdapter;
import com.dunqi.gpm.cangxi.home.bean.Project;
import com.dunqi.gpm.cangxi.home.constance.Constance;
import com.dunqi.gpm.cangxi.home.eventbus.FinishAndRefresh;
import com.dunqi.gpm.cangxi.home.fragment.HomeFragment;
import com.dunqi.gpm.cangxi.home.fragment.ProblemConsortFragment2;
import com.dunqi.gpm.cangxi.home.fragment.ProjectAllProgressFragment;
import com.dunqi.gpm.cangxi.home.fragment.ProjectBasicInfoFragment;
import com.dunqi.gpm.cangxi.home.fragment.ProjectTrendFragment;
import com.dunqi.gpm.cangxi.home.fragment.UpListFragment;
import com.dunqi.gpm.cangxi.home.fragment.YearPlanListFragment;
import com.dunqi.gpm.cangxi.home.widget.TwoInOne;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

@SuppressLint("CheckResult")
public class ProjectDetailActivity extends BaseAct implements TabLayout.OnTabSelectedListener {

    public static final int TYPE_AUDIT = 1;//审核
    public static final int TYPE_COMMENT = 2;//评价

    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.three_in_one)
    ThreeInOne threeInOne;
    @BindView(R.id.two_in_one)
    TwoInOne twoInOne;
    @BindView(R.id.comment_tv)
    TextView commentTv;
    ArrayList<Fragment> fragments = new ArrayList<>();
    @BindView(R.id.progress_report)
    DrawLeftRadioButton progressReport;
    @BindView(R.id.apply_applicaiton)
    DrawLeftRadioButton applyApplicaiton;
    @BindView(R.id.progress_container)
    LinearLayout progressContainer;
    private Project item_project;
    private int index;
    @Override
    protected void refreshData(Bundle savedInstanceState) {
    }

    @Override
    protected void initUiAndListener() {
        Intent intent = getIntent();

        EventBus.getDefault().register(this);

        item_project = (Project) intent.getSerializableExtra(Constance.PROJECT);
        index = intent.getIntExtra(Constance.POSITION, 0);

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在拉取数据");
        ApiFactory.getInstance()
                .queryBaseInfo(item_project.getProjectId())
                .compose(RxSchedulers.io_main())
                .subscribe(data -> {
                    item_project = data.getData();
                    init();
                    dialog.dismiss();
                }, throwable -> {
//                    t("获取失败");
                    dialog.dismiss();
                });
    }

    public final static String[] TITLES = {"基本信息", "年度计划", "项目进度", "项目动态", "问题协调", "点赞列表"
            //原本的顺序
            //  "基本信息", "项目简介", "年度计划", "前期信息", "项目进度", "项目动态", "问题协调", "项目监控","点赞列表"
            //  ,"工作批示"//            "项目审批",//            "项目动态", "项目日报", "项目批示", "监控视频"
    };

    private void init() {
        titleBar.setTitle(item_project.getProjectName());
        //基本信息
        fragments.add(ProjectBasicInfoFragment.newInstance(item_project));
//        //简介
        //     fragments.add(ProjectDescriptionFragment.newInstance(item_project));
//        //年度计划
        fragments.add(YearPlanListFragment.newInstance(item_project));
/*//        //前期信息    项目前期和项目进度合并到一个页面
        fragments.add(EarlyInfoFragment.newInstance(item_project));
//        //项目进度
        fragments.add(ProjectTimelineFragment.newInstance(item_project));*/
        //项目进度
        fragments.add(ProjectAllProgressFragment.newInstance(item_project));
//        //项目动态
        fragments.add(ProjectTrendFragment.newInstance(item_project.getProjectId()));
        //问题协调  跳转界面
        fragments.add(ProblemConsortFragment2.newInstance(item_project.getProjectId(), item_project.getProjectName()));
//    //    项目监控
//        fragments.add(VideoListFragment.newInstance(item_project.getProjectId()));
        //点赞列表
        fragments.add(UpListFragment.newInstance(item_project.getProjectId()));
        if (viewPager.getAdapter() == null) {
            viewPager.setAdapter(new ViewPagerFragmentAdapter(getSupportFragmentManager(), fragments, TITLES));
            tabLayout.setupWithViewPager(viewPager);
        }
        tabLayout.getTabAt(index).select();
        tabLayout.addOnTabSelectedListener(this);
        int homeMenuId = HomeFragment.homeMenuId;
        if (homeMenuId == Constance.MainMenu.MENU_DIVIDED_PROJECT ||
                homeMenuId == Constance.MainMenu.MENU_QUERY_PROJECT ||
                homeMenuId == Constance.MainMenu.MENU_MY_ATTENTION && UserUtil.userIsLeader()) {
            threeInOne.setVisibility(View.VISIBLE);
            threeInOne.setLeftChecked(item_project.getConcerned() == 1);
            threeInOne.setRightText("批示");
        }
        if (homeMenuId == 11 && (UserUtil.userFromNdrcOrg() || UserUtil.userFromRespOrg())) {
            threeInOne.setVisibility(View.VISIBLE);
            threeInOne.setGoneLeft2();
            threeInOne.setLeftChecked(item_project.getConcerned() == 1);
            threeInOne.setRightText("留言");
        }
        threeInOne.setOnClickListener(v -> {
            final ProgressDialog dialog = ProgressDialog.show(getActivity(), "提示", "请稍后...");
            if (threeInOne.isLeftChecked()) {
                favorite(dialog);
            } else {
                favoriteCancel(dialog);
            }
        }, v -> up(), v -> {
            int msgType;
            if (UserUtil.userFromRespOrg() || UserUtil.userFromNdrcOrg()) {
                msgType = 2;
            } else {
                msgType = 1;
            }
            InstructionsActivity.start(getActivity(), item_project.getProjectId(), Constance.INSTRUCTION_TYPE_PROJECT, msgType, 0l);
        });

        final int auditStatus = item_project.getAuditStatus();
        if (HomeFragment.homeMenuId == 12 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
            twoInOne.setVisibility(View.VISIBLE);
        }
        if (HomeFragment.homeMenuId == 15 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
            twoInOne.setVisibility(View.VISIBLE);
        }
        progressReport.setOnClickListener(v -> {
            //填写新的进展汇报
            UpdateProgressActivity.start(getActivity(), item_project.getProjectId(), 0);
        });
        applyApplicaiton.setOnClickListener(v -> {
            //申请结项
            UpdateProgressActivity.start(getActivity(), item_project.getProjectId(), 1);
        });
        twoInOne.setOnTwoClickListener(v -> {
            //审核
            if (HomeFragment.homeMenuId == 12 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
                ProjectBaseAutidActivity.start(getActivity(), item_project, 1, ProjectAutidRequestCode);
            }
            if (HomeFragment.homeMenuId == 15 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
                ProjectPlanYearAutidActivity.start(getActivity(), item_project, 1, ProjectAutidRequestCode);
            }
        }, v -> {
            if (HomeFragment.homeMenuId == 12 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
                //审核不通过
                ProjectBaseAutidActivity.start(getActivity(), item_project, 0, ProjectAutidRequestCode);
            }
            if (HomeFragment.homeMenuId == 15 && UserUtil.userFromNdrcOrg() && auditStatus == 1) {
                ProjectPlanYearAutidActivity.start(getActivity(), item_project, 0, ProjectAutidRequestCode);
            }
        });
        //项目评价
        commentTv.setOnClickListener(v -> {
        });
    }

    private void favoriteCancel(final ProgressDialog dialog) {
        ApiFactory.getInstance()
                .cancelFavorite(item_project.getProjectId())
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new ComObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }

                    @Override
                    public void onSuccess(Object o) {
                        t("取消成功");
                        threeInOne.setLeftChecked(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        threeInOne.setLeftChecked(true);
                    }

                    @Override
                    public void onFinal() {
                        dialog.dismiss();
                    }
                });
    }

    private void favorite(final ProgressDialog dialog) {
        ApiFactory.getInstance()
                .addFavorite(item_project.getProjectId())
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new ComObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }


                    @Override
                    public void onSuccess(Object o) {
                        t("关注成功");
                        threeInOne.setLeftChecked(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        threeInOne.setLeftChecked(false);
                    }

                    @Override
                    public void onFinal() {
                        dialog.dismiss();
                    }
                });
    }

    // dianzan
    private void up() {
        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在点赞");
        ApiFactory.getInstance()
                .up(item_project.getProjectId(), null)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new ComObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }

                    @Override
                    public void onSuccess(Object o) {
                        t("点赞成功");
                    }

                    @Override
                    public void onFinal() {
                        dialog.dismiss();
                    }
                });
    }

    int ProjectAutidRequestCode = 136;

    @Subscribe
    public void onEventMainThread(FinishAndRefresh finishAndRefresh) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ProjectAutidRequestCode) {
            if (data != null) {
                if (twoInOne == null) {
                    return;
                }
                twoInOne.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_project_detail;
    }

    public static void start(Context context, Project project, int position) {
        Intent intent = new Intent(context, ProjectDetailActivity.class);
        intent.putExtra(Constance.PROJECT, project);
        intent.putExtra(Constance.POSITION, position);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        if (position == 3) {
            //前期信息
        }
//        if (position == 6) {
//            QuestionListActivity.start(getActivity(), item_project);
//        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }
}